using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MVCWeb.Models.ViewData;
using MVCWeb.Models;
using System.IO;
using System.Configuration;
using System.Drawing;
using MVCWeb.Helpers;
using System.Drawing.Imaging;

namespace MVCWeb.Controllers
{
    public class NewsController : BaseController
    {
        //
        // GET: /News/
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Index()
        {
            if (Session["CommunityId"] == null)
            {
                return RedirectToAction("Index", "SelectCommunity", new { returnUrl = Request.RawUrl });
            }

            int communityId = Convert.ToInt32(Session["CommunityId"]);

            return View(this.dc.News.Where(n => n.CommunityId == communityId).OrderByDescending(n => n.PublishedDate).ToList());
        }

        //
        // GET: /News/
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult LeisureLifeNewsIndex()
        {
            return View(this.dc.News.Where(n => n.CommunityId == 0 || n.CommunityId.HasValue == false).OrderByDescending(n => n.PublishedDate).ToList());
        }

        //
        // GET: /News/Create
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Create()
        {
            if (Session["CommunityId"] == null)
            {
                return RedirectToAction("Index", "SelectCommunity", new { returnUrl = Request.RawUrl });
            }

            NewsNewViewData data = new NewsNewViewData();
            data.News = new News();
            return View(data);
        }

        //
        // GET: /News/Create
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult CreateLeisureLifeNews()
        {
            NewsNewViewData data = new NewsNewViewData();
            data.News = new News();
            return View(data);
        }

        //
        // POST: /News/Create
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators, PropertyManagers"), ValidateInput(false)]
        public ActionResult Create(News newsToCreate, FormCollection collection)
        {
            try
            {
                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file];
                    if (hpf.ContentLength == 0)
                        continue;

                    const string savePath = @"Uploads\Images\News\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = Path.GetFileNameWithoutExtension(hpf.FileName) + file_append + extension;
                    }

                    // need to caculate correct width and height
                    const int widthMax = 200;
                    const int heightMax = 200;

                    string savedFileName = Path.Combine(physicPath, sFilename);
                    hpf.SaveAs(savedFileName);

                    Image fullPicture;
                    try
                    {
                        // New image size.
                        fullPicture = new Bitmap(savedFileName);
                        Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                        fullPicture.Dispose();

                        // Delete original image.
                        if (System.IO.File.Exists(savedFileName))
                        {
                            System.IO.File.Delete(savedFileName);
                        }

                        string ext = hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                        switch (ext.ToLower())
                        {
                            case ".jpg":
                                original.Save(savedFileName, ImageFormat.Jpeg);
                                break;
                            case ".png":
                                original.Save(savedFileName, ImageFormat.Png);
                                break;
                            case ".gif":
                                original.Save(savedFileName, ImageFormat.Gif);
                                break;
                            case ".bmp":
                                original.Save(savedFileName, ImageFormat.Bmp);
                                break;
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in create thumbnail: " + ex.Message);
                    }

                    newsToCreate.ImageUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }
                if (collection["Type"] == "LeisureLifeNews")
                {
                    newsToCreate.CommunityId = null;
                }

                newsToCreate.Title = HttpUtility.HtmlEncode(collection["Title"]);
                newsToCreate.SubTitle = HttpUtility.HtmlEncode(collection["SubTitle"]);
                newsToCreate.CompanyId = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]);
                newsToCreate.PublishedDate = DateTime.Now;
                newsToCreate.Description = HttpUtility.HtmlEncode(newsToCreate.Description);
                this.dc.News.InsertOnSubmit(newsToCreate);
                this.dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                return Redirect(Request.RawUrl);
            }
            catch
            {
                NewsNewViewData data = new NewsNewViewData();
                data.News = new News();
                return View(data);
            }
        }

        //
        // GET: /News/Print/5
        public ActionResult Print(int id)
        {
            NewsNewViewData data = new NewsNewViewData();
            data.News = this.dc.News.Single(n => n.NewsId == id);
            return View("Print", "Blank", data);
        }

        //
        // GET: /News/ViewDetail/5
        public ActionResult ViewDetail(int id)
        {
            try
            {
                Community community;
                MVCWeb.Models.User user = new MVCWeb.Models.User();
                int communityId = 0;
                try
                {
                    MembershipUser membershipUser = Membership.GetUser();
                    Guid membershipId = new Guid(membershipUser.ProviderUserKey.ToString());
                    user = dc.Users.Where<MVCWeb.Models.User>(u => u.MembershipId == membershipId).First<MVCWeb.Models.User>();
                    community = dc.Communities.First<Community>(c => c.UserId == user.UserId || c.ManagerId == user.UserId);
                    communityId = community.CommunityId;
                    ViewData["CommunityId"] = communityId;
                }
                catch
                {
                    UsersInCommunity userInCommunity = dc.UsersInCommunities.First(x => x.UserId == user.UserId);
                    community = dc.Communities.First(x => x.CommunityId == userInCommunity.CommunityId);
                    communityId = community.CommunityId;
                    ViewData["CommunityId"] = communityId;
                }

                if (string.IsNullOrEmpty(community.ImgUrl) == false)
                {
                    ViewData["CommunityImgUrl"] = string.Format("<img alt='' class='CommunityImage'  src='{0}' />", Url.Content("~/" + community.ImgUrl));
                }
                else
                {
                    ViewData["CommunityImgUrl"] = string.Empty;
                }
            }
            catch { }


            NewsNewViewData data = new NewsNewViewData();
            data.News = this.dc.News.Single(n => n.NewsId == id);
            return View(data);
        }

        //
        // GET: /News/Edit/5
        [AcceptVerbs(HttpVerbs.Get), Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult Edit(int id)
        {
            NewsNewViewData data = new NewsNewViewData();
            data.News = this.dc.News.Single(n => n.NewsId == id);
            return View(data);
        }

        //
        // POST: /News/Edit/5
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators, PropertyManagers"), ValidateInput(false)]
        public ActionResult Edit(int id, News newsToEdit, FormCollection collection)
        {
            try
            {
                newsToEdit = dc.News.Single(n => n.NewsId == id);

                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase hpf = Request.Files[file];
                    if (hpf.ContentLength == 0)
                        continue;

                    FileInfo oldFile = new FileInfo(Server.MapPath("~/" + newsToEdit.ImageUrl));
                    if (oldFile.Exists)
                    {
                        oldFile.Delete();
                    }

                    

                    const string savePath = @"Uploads\Images\News\";

                    string physicPath = AppDomain.CurrentDomain.BaseDirectory + savePath;
                    if (!Directory.Exists(physicPath))
                    {
                        Directory.CreateDirectory(physicPath);
                    }

                    string sFilename = Path.GetFileName(hpf.FileName);

                    string extension = Path.GetExtension(hpf.FileName).ToLower();

                    int file_append = 0;
                    while (System.IO.File.Exists(Path.Combine(physicPath, sFilename)))
                    {
                        file_append++;
                        sFilename = Path.GetFileNameWithoutExtension(hpf.FileName) + file_append + extension;

                    }

                    string savedFileName = Path.Combine(physicPath, sFilename);

                    hpf.SaveAs(savedFileName);


                    // need to caculate correct width and height
                    const int widthMax = 200;
                    const int heightMax = 200;

                    savedFileName = Path.Combine(physicPath, sFilename);
                    hpf.SaveAs(savedFileName);

                    Image fullPicture;
                    try
                    {
                        // New image size.
                        fullPicture = new Bitmap(savedFileName);
                        Image original = ImageHelper.ResizeImage(fullPicture, widthMax, heightMax, ImageResizeOption.MaintainAspectWidth);
                        fullPicture.Dispose();

                        // Delete original image.
                        if (System.IO.File.Exists(savedFileName))
                        {
                            System.IO.File.Delete(savedFileName);
                        }

                        string ext = hpf.FileName.Substring(hpf.FileName.LastIndexOf('.'));
                        switch (ext.ToLower())
                        {
                            case ".jpg":
                                original.Save(savedFileName, ImageFormat.Jpeg);
                                break;
                            case ".png":
                                original.Save(savedFileName, ImageFormat.Png);
                                break;
                            case ".gif":
                                original.Save(savedFileName, ImageFormat.Gif);
                                break;
                            case ".bmp":
                                original.Save(savedFileName, ImageFormat.Bmp);
                                break;
                        }
                        original.Dispose();
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error in create thumbnail: " + ex.Message);
                    }


                    newsToEdit.ImageUrl = Url.Content("~/" + savePath.Replace('\\', '/') + sFilename);
                }

                newsToEdit.Title = HttpUtility.HtmlEncode(collection["Title"]);
                newsToEdit.SubTitle = HttpUtility.HtmlEncode(collection["SubTitle"]);
                newsToEdit.CompanyId = Convert.ToInt32(ConfigurationManager.AppSettings["CompanyId"]);
                newsToEdit.Description = HttpUtility.HtmlEncode(collection["Description"]);
                dc.SubmitChanges();
                if (collection["IsRedirectToView"].Equals("true"))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    return Redirect(Request.RawUrl);
                }
            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /News/Delete/5
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators")]
        public ActionResult Delete(int id)
        {
            try
            {
                News news = dc.News.Single(x => x.NewsId == id);
                FileInfo oldFile = new FileInfo(Server.MapPath("~/" + news.ImageUrl));
                if (oldFile.Exists)
                {
                    oldFile.Delete();
                }
                dc.News.DeleteOnSubmit(news);
                dc.SubmitChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: /News/Edit/5
        [Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult ChangeStatus()
        {
            return View();
        }

        // ChangeStatus
        [AcceptVerbs(HttpVerbs.Post), Authorize(Roles = "Administrators, PropertyManagers")]
        public ActionResult ChangeStatus(int id)
        {
            News news = this.dc.News.Single(x => x.NewsId == id);
            news.Active = !news.Active;
            this.dc.SubmitChanges();
            return View();
        }
    }
}
